package com.carbeauty.web.listener;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.carbeauty.image.Constants;



public class ImageServlet extends HttpServlet{
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("image/jpeg; charset=GBK");
		//得到输出流
		ServletOutputStream stream = resp.getOutputStream();
		FileInputStream in =null;
		//取得服务器上的图片路径
		String imageId = req.getParameter("id");
		
		String url = req.getRequestURI();
		String id = url.substring(url.indexOf("id/")+3, url.length());
		//TODO:这里从数据库或者别的方式 通过ID 找到 所对应的服务器上的绝对路径
		String newFilePath = (id.startsWith("Temp_")?Constants.FILE_UPLOAD_TEMP_DIR:Constants.FILE_UPLOAD_DIR)+"/"+(id.indexOf(".")!=-1?(id):(id+".jpg"));;
		
		File inputFile = new File(newFilePath);
		//得到输入流
		in = new FileInputStream(inputFile);
		if (in != null) {
			byte[] b = new byte[1024];
			int len = 0;
			while ((len = in.read(b)) != -1) {
				//写入输出流
				stream.write(b, 0, len); 
		    }
		 }
		stream.flush();
		//关闭输出流
		stream.close();
		//关闭输入流
		in.close();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doPost(req, resp);
	}

}
